#!/usr/bin/env python3
"""
数据预处理管道系统 - Web界面启动脚本

快速启动Web界面的便捷脚本
"""

import os
import sys
import subprocess
import webbrowser
import time
from pathlib import Path

def check_dependencies():
    """检查依赖包是否安装"""
    required_packages = [
        'flask',
        'flask_socketio', 
        'pandas',
        'numpy',
        'openpyxl',
        'scikit-learn',
        'scipy'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    return missing_packages

def install_dependencies():
    """安装缺失的依赖包"""
    print("正在安装Web界面依赖包...")
    
    try:
        subprocess.check_call([
            sys.executable, '-m', 'pip', 'install', '-r', 'requirements_web.txt'
        ])
        print("✓ 依赖包安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 依赖包安装失败: {e}")
        return False

def start_web_server():
    """启动Web服务器"""
    print("🚀 启动数据预处理管道Web界面...")
    print("=" * 50)
    print("🌐 本地访问: http://localhost:5000")
    print("📱 局域网访问: http://你的IP地址:5000")
    print("🛑 停止服务: 按 Ctrl+C")
    print("=" * 50)
    
    # 延迟打开浏览器
    def open_browser():
        time.sleep(2)
        try:
            webbrowser.open('http://localhost:5000')
            print("✓ 已自动打开浏览器")
        except Exception as e:
            print(f"⚠️  无法自动打开浏览器: {e}")
            print("请手动访问: http://localhost:5000")
    
    import threading
    browser_thread = threading.Thread(target=open_browser)
    browser_thread.daemon = True
    browser_thread.start()
    
    # 启动Flask应用
    try:
        from web_app import app, socketio
        socketio.run(app, debug=False, host='0.0.0.0', port=5000)
    except KeyboardInterrupt:
        print("\n\n👋 Web服务已停止")
    except Exception as e:
        print(f"\n❌ 启动失败: {e}")
        print("\n💡 解决建议:")
        print("1. 检查端口5000是否被占用")
        print("2. 确保所有依赖包已正确安装")
        print("3. 检查防火墙设置")
        print("4. 尝试以管理员权限运行")

def main():
    """主函数"""
    print("🚀 数据预处理管道系统 - Web界面启动器")
    print("=" * 50)
    
    # 检查依赖
    missing = check_dependencies()
    
    if missing:
        print(f"⚠️  缺少依赖包: {', '.join(missing)}")
        
        install_choice = input("是否自动安装缺失的依赖包? (y/n): ").strip().lower()
        
        if install_choice in ['y', 'yes', '是']:
            if not install_dependencies():
                print("❌ 依赖包安装失败，请手动安装:")
                print(f"pip install -r requirements_web.txt")
                return
        else:
            print("请手动安装依赖包后重新运行:")
            print("pip install -r requirements_web.txt")
            return
    
    # 检查核心文件
    required_files = [
        'web_app.py',
        'templates/index.html',
        'static/css/style.css',
        'static/js/app.js'
    ]
    
    missing_files = []
    for file_path in required_files:
        if not Path(file_path).exists():
            missing_files.append(file_path)
    
    if missing_files:
        print(f"❌ 缺少必要文件: {', '.join(missing_files)}")
        return
    
    # 创建必要目录
    os.makedirs('uploads', exist_ok=True)
    os.makedirs('output', exist_ok=True)
    
    print("✓ 环境检查完成")
    
    # 启动Web服务器
    start_web_server()

if __name__ == "__main__":
    main()